package com.gviiii.pprf.task;

import com.gviiii.pprf.netty.*;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Map;

import static com.gviiii.pprf.common.Rf.getSnr;

@Component
public class RFTask {

    @Resource
    private MsgTagCacheService msgTagCacheService;

    /**
     * 定时任务 获取设备中的卡号
     */
    @Scheduled(cron = "0/3 * * * * ?")
    public void pushData() {
        NettyMessage message = new NettyMessage();
        Map<String, Integer> msgTags = RfNioClient.getMsgTags();
        if (msgTagCacheService.getMsgTagCode()!=null) {
            Integer i = msgTagCacheService.getMsgTagCode();
            if (i != null) {
                switch (i) {
                    case 0:
                        message.setHeader(Header.CONNECTED_MSG);
                        RfNioClient.send(message);
                        msgTagCacheService.removeMsgTag();
                        break;
                    case 1: {
                        sendSnrs(message, msgTags, Header.RECEIVE_PERSONCARD_MSG);
                    }
                    break;
                    case 2: {
                        sendSnrs(message, msgTags, Header.RECEIVE_POSITIONCARD_MSG);
                    }
                    break;
                    case 3: {
                        sendSnrs(message, msgTags, Header.RECEIVE_POSITIONCARDREUSE_MSG);
                    }
                    break;
                    default:
                        break;
                }
            }
        }
    }

    /**
     * 发送卡号
     *
     * @param message
     * @param msgTags
     * @param receivePositioncardreuseMsg
     */
    private void sendSnrs(NettyMessage message, Map<String, Integer> msgTags, String receivePositioncardreuseMsg) {
        message.setHeader(receivePositioncardreuseMsg);
        String s = getSnrs();
        if (!StringUtils.isEmpty(s)) {
            message.setBody(s);
        }
        RfNioClient.send(message);
        msgTags.remove(RfChannelHandler.MSG_TAG);
    }

    /**
     * 获取卡号
     *
     * @return
     */
    private String getSnrs() {
        String s = getSnr();
        String[] split = s.split("\\|");
        StringBuffer sb = new StringBuffer();
        if (split.length > 0) {
            if ("0".equals(split[0])) {
                String s1 = split[1];
                for (int i = s1.length() / 2 - 1; i >= 0; i--) {
                    String substring = s1.substring(2 * i, 2 * i + 2);
                    sb.append(substring);
                }
//                RfNioClient.send((Long.valueOf(sb.toString(), 16).toString()));
                return Long.valueOf(sb.toString(), 16).toString();
//                RfNioClient.send(message);
            }
        }
        return Long.valueOf(1).toString();
    }
}
